const express = require('express')
const app = express()
const cors = require('cors')
const bodyParse = require("body-parser")
app.use(cors())
const {expressjwt: jwt} = require('express-jwt')
const  {jwtSecretKey } = require('./config/jwtSecretKey')
const { Account} = require('./config/sequelize.js') //account表
// 解析json数据格式
app.use(bodyParse.json());
// 解析urlencoded字符数据格式 false：返回的对象属性值为string或者array，true：任何类型
app.use(bodyParse.urlencoded({ extended: false }));

// 用户认证中间件
app.use(jwt({ secret: jwtSecretKey, algorithms: ['HS256'] }).unless(
  {
    path: [
      /^\/api\/user\/v1\/register/, //注册
      /^\/api\/user\/v1\/login/, //登录
      /^\/api\/notify\/v1\//, // 验证码
      /^\/api\/wxlogin\/v1\//, // 微信登录
      /^\/api\/user\/v1\/forget/ ,//, // 微信登录
      /^\/api\/order\/v1\/pay/,  //微信支付
    ],
  })
 );
// 验证码通知相关
const notifyRouter = require('./router/notify.js')
app.use('/api/notify/v1', notifyRouter)

const userRouter = require('./router/user.js')
app.use('/api/user/v1', userRouter)

// 微信接入接口
const wxLoginRouter = require('./router/wxlogin.js')
app.use('/api/wxlogin/v1', wxLoginRouter)

// 订单相关的接口
const orderRouter = require('./router/order.js')
app.use('/api/order/v1', orderRouter)

// app.get('/api/user/v1/login', async (req, res) => {
//   const dbRes = await Account.create({ name: '⽼⑦' })
//   res.send('插⼊成功')
// });
// app.get('/test', async (req, res) => {
//   // console.log(req.query)
//   res.send('测试接口')
// });
// 错误中间件
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
  return res.send({code:-1,data:null,msg:'请先登录！'})
   }
  //其他的错误
  res.send({code:-1,data:null,msg:err.message})
})
app.listen('8080', ()=>{
  console.log('服务启动在127.0.0.1:8080')
})

